package cn.ccenjie.wsy.config;

import cn.ccenjie.wsy.dao.UserDao;
import cn.ccenjie.wsy.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;

@Slf4j
public class SysUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User db = userDao.findOne(Example.of(User.build().sUserName(username))).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        return new SysUserDetails(db.getId(), db.getUsername(), new BCryptPasswordEncoder().encode(db.getPassword()));
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("社交登录，获取的用户ID：{}", userId);
        User db = userDao.findOne(Example.of(User.build().sId(userId))).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        return new SysUserDetails(db.getId(), db.getUsername(), new BCryptPasswordEncoder().encode(db.getPassword()));
    }
}
